package com.bootdo.rabbitMQ.direct;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author wukq
 * @Date: 2021/4/10 8:53
 * @Description: 队列持久化需要在声明队列时添加参数 durable=True，这样在rabbitmq崩溃时也能保存队列
 * 仅仅使用durable=True ，只能持久化队列，不能持久化消息
 * 消息持久化需要在消息生成时，添加参数 properties=pika.BasicProperties(delivery_mode=2)
 * channel.basic_publish(exchange='',
 * routing_key='hello',
 * body='hello',
 * properties=pika.BasicProperties(
 * delivery_mode=2,  # make message persistent
 * ))
 * <p>
 * # 增加properties，这个properties 就是消费端 callback函数中的properties
 * # delivery_mode = 2  持久化消息
 */
@Configuration
public class DirectRabbitConfig {
  /**
   * 交换机
   */
  @Bean
  DirectExchange directExchange2() {
    return new DirectExchange(DirectConstant.EXCHANGE);
  }

  /**
   * 声明队列,durable队列持久化
   * durable true if we are declaring a durable queue (the queue will survive a server restart)
   */
  @Bean
  public Queue directQueue2() {
    return new Queue(DirectConstant.QUEUE_DIRECT, true);
  }

  /**
   * 绑定路由
   */
  @Bean
  public Binding bindingDirectPSUH() {
    return BindingBuilder.bind(directQueue2()).to(directExchange2()).with(DirectConstant.QUEUE_PUSH);
  }

/**Only one ConfirmCallback is supported by each RabbitTemplate，sender里面开启了确认机制，config就不能开启
 * */
//  @Bean
//  public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) {
//    RabbitTemplate rabbitTemplate = new RabbitTemplate();
//    rabbitTemplate.setConnectionFactory(connectionFactory);
//    //设置开启Mandatory,才能出发回调函数，无论消息推送结果怎么样都强制调用回调函数
//    rabbitTemplate.setMandatory(true);
//    rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
//      @Override
//      public void confirm(CorrelationData correlationData, boolean ack, String cause) {
//        System.out.println("ConfirmCallback:     " + "相关数据：" + correlationData);
//        System.out.println("ConfirmCallback:     " + "确认情况：" + ack);
//        System.out.println("ConfirmCallback:     " + "原因：" + cause);
//
//      }
//    });
//
//    rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
//      @Override
//      public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
//        System.out.println("ReturnCallback:     " + "消息：" + message);
//        System.out.println("ReturnCallback:     " + "回应码：" + replyCode);
//        System.out.println("ReturnCallback:     " + "回应信息：" + replyText);
//        System.out.println("ReturnCallback:     " + "交换机：" + exchange);
//        System.out.println("ReturnCallback:     " + "路由键：" + routingKey);
//
//      }
//    });
//    return rabbitTemplate;
//  }
}
